import 'package:flutter/material.dart';

import '../extentions/build_context_extentions.dart';

class ModuleEntranceWidget extends StatelessWidget {
  final ModuleItem module;
  final double iconSize;
  final double? width;
  final double? height;
  final BoxDecoration? decoration;
  final TextStyle style;
  final double space;

  const ModuleEntranceWidget({
    Key? key,
    required this.module,
    this.iconSize = 28,
    this.width,
    this.height,
    this.decoration,
    this.style = const TextStyle(
      fontSize: 12,
      color: Color(0xff898989),
      fontWeight: FontWeight.bold,
    ),
    this.space = 4.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        width: width,
        height: height,
        decoration: decoration,
        child: Center(child: buildContent(context)),
      ),
      onTap: () {
        onTap(context);
      },
    );
  }

  Widget buildContent(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        if (module.icon != null)
          Icon(
            module.icon,
            size: iconSize,
          )
        else if (module.image != null)
          Image.asset(
            context.imageAsset(module.image!),
            width: iconSize,
            height: iconSize,
          ),
        if (module.hasPrefix) SizedBox(height: space),
        Text(module.text, style: style)
      ],
    );
  }

  void onTap(BuildContext context) {
    if (module.precondition != null) {
      module.precondition!(context).then((value) {
        if (value == true) {
          if (module.onTap != null) {
            module.onTap!(context);
          } else {
            context.goto(module.builder!(context));
          }
        }
      });
    } else {
      if (module.onTap != null) {
        module.onTap!(context);
      } else if (module.builder != null) {
        context.goto(module.builder!(context));
      }
    }
  }
}

typedef Future<bool> EnterModulePrecondition(BuildContext context);

typedef void ModuleTapCallback(BuildContext context);

class ModuleItem {
  final String text;
  final String? image;
  final IconData? icon;
  final WidgetBuilder? builder;
  final ModuleTapCallback? onTap;
  final EnterModulePrecondition? precondition;
  final dynamic extra;

  const ModuleItem({
    required this.text,
    this.image,
    this.icon,
    this.builder,
    this.onTap,
    this.precondition,
    this.extra,
  }) : assert(builder != null || onTap != null);

  get hasPrefix => image != null || icon != null;
}
